<template>
	<view class="main-cont">
		<view class="content">
			<view class="box box-tb box-align-center box-pack-start" v-if="showlogin">
				<view class="login-tip"> 欢迎登录 </view>
				<view class="name mt20"> 五育通•劳动教育云 </view>
				<u-button :custom-style="loginbtnCustomStyle" class="mb20" :ripple="true" ripple-bg-color="#b0c1ff"
					:loading="btnloading==true" @click="goLogin">登 录</u-button>

				<u-button :custom-style="wxCustomStyle" @click="getUserProfile" :ripple="true">
					<u-image width="30px" height="30px"
						src="/static/icon_wx.png">
					</u-image>
					<view style="font-size: 14px;color: #fff !important;margin-left: 5px;">微信快捷登录</view>
				</u-button>
				<!-- <view class="change" @click="changeStatus">
					{{changeLogin == true?'验证码登录':'账号登录'}}
				</view> -->
				<!-- <view class="fixed">
					<u-button :ripple="true" @click="getUnionidOnly"
						:custom-style="btnOpen" class="u-hairline-border">
						<u-image width="30px" height="30px"
							src="/static/icon_wx.png">
						</u-image>
						<view style="font-size: 14px;color: #fff !important;margin-left: 5px;">微信快捷登录</view>
					</u-button>
				</view> -->
				<!-- <u-link href="###" :under-line="true" color="#fff" ></u-link> -->
				<view class="register" @click="regist">注 册</view>
			</view>

		</view>
		<u-toast ref="uToast" />
		<u-top-tips ref="uTips"></u-top-tips>
	</view>
</template>

<script>
	import { checkUser } from "@/hooks/index.js"
	export default {
		data() {
			return {
				form: {
					usercode: "",
					pwd: "",
					code: ""
					// usercode:"19520467644",
					// pwd:"840931"
					// usercode:"15710077317",
					// pwd:"729215",
					// usercode:'16601290636',
					// pwd:'237411'
				},
				sendcodetext: '获取验证码',
				miao: 180,
				able: false,
				customStyle: {
					padding: "40rpx",
					color: "#fff"
				},
				customStyles: {
					padding: "0 100rpx 0 40rpx",
					color: "#fff"
				},
				customStyleSfzh: {
					width: "190px",
					padding: "0 40rpx",
					color: "#fff"
				},
				placeholderStyle: {
					color: "#fff"
				},
				time: null,
				loginbtnCustomStyle: {
					width: '560rpx',
					height: '86rpx',
					lineHeight: '86rpx',
					background: 'linearGradient(0deg, #DFE2F5, #FFFFFF)',
					boxShadow: '0px 14rpx 40rpx 0px #626BF1',
					borderRadius: '43rpx',
					fontSize: '28rpx',
					textAlign: 'center',
					color: '#858bec',
					marginTop: '150rpx'
				},
				wxCustomStyle: {
					width: '560rpx',
					height: '86rpx',
					lineHeight: '86rpx',
					background: '#16d26d',
					// boxShadow: '0px 14rpx 40rpx 0px #16d26d',
					borderRadius: '43rpx',
					fontSize: '28rpx',
					textAlign: 'center',
					color: '#fff',
					marginTop: '10rpx',
					border: 'none'
				},
				btnloading: false,
				user: uni.getStorageSync('user'),
				role: uni.getStorageSync('role'),
				roles: uni.getStorageSync('roles'),
				accont: uni.getStorageSync('accont'),
				openid: '',
				unionid: '',
				showlogin: true,
				changeLogin: true,
				authcode: '',
				btnOpen: {
					backgroundColor: '#888bf3',
					color: '#888bf3',
					fontSize: '24rpx'
				},
				userInfo: {
					width: "80px !important",
					height: "80px !important",
					border: "none"
				},
				socketTask: null,
				loginServerip: 'wss://www.wytldy.com:8765/WebSocketServer',
				is_open_socket: false,
				token: null //扫码登录标识
			}
		},
		onShareAppMessage(res) {
			return {
				title: '欢迎加入【五育通劳动教育云】~',
				path: '/team/tr/invite',
				imageUrl: 'https://yh-sys.oss-cn-beijing.aliyuncs.com/2AA82D3CF32F47D0BBFBC6037E73D503join.png?Expires=4792987242&OSSAccessKeyId=LTAI4GL8SwAiLh3sSPXDS7z9&Signature=skoxCO1pZ1kn3DJIiBTnGM%2FO2oY%3D'
			}
		},
		onShareTimeline() {
			return {
				title: '欢迎加入【五育通劳动教育云】~',
				imageUrl: 'https://yh-sys.oss-cn-beijing.aliyuncs.com/2AA82D3CF32F47D0BBFBC6037E73D503join.png?Expires=4792987242&OSSAccessKeyId=LTAI4GL8SwAiLh3sSPXDS7z9&Signature=skoxCO1pZ1kn3DJIiBTnGM%2FO2oY%3D'
			}
		},
		onLoad(opt) {
			this.token = opt.scene
			if (!this.accont) {} else {
				if (this.accont.pwd != '') {
					this.pwdLogin()
				} else {
					this.codeLogin()
				}
			}
			this.getUnionidOnly(opt.scene);
			// this.form.usercode = uni.getStorageSync('phone');
			// checkUser()
		},
		methods: {
			//push
			loginPush(scene, openId) {
				//console.log("loginPush()");
				let url = '/wx/login/push';
				let params = {
					cid: scene,
					openID: openId
				}
				//console.log(params);
				this.$api.post(url, params).then(res => {
					//console.log(res);
					//console.log("loginPush()成功返回");
				})
			},
			//扫码登录
			socketLogin() {
				//console.log('扫码登录');
				var _this = this;
				this.socketTask = uni.connectSocket({
					url: _this.loginServerip + "/" + _this.token,
					success(data) {}
				});
				this.socketTask.onOpen((res) => {
					//console.log(res);
					_this.is_open_socket = true;
					let msg = {
						"cmd": "login",
						"openid": _this.openid
					};
					_this.socketTask.send({
						data: JSON.stringify(msg),
						async success() {
							this.socketTask.onClose()
							//this.closeSocket();
							// _this.loginPush();
						},
					});
				});
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					//console.log("已经被关闭了")
				});
			},
			goLogin(){
				uni.navigateTo({
					url:'/pages/index/login'
				})
			},
			getUserProfile(e) {
				uni.getUserProfile({
					desc: '获取用户信息登录',
					success: (res) => {
						//console.log(res);
						uni.setStorage({
							key:'wxUser',
							data:res.userInfo
						})
						// this.userinfo.icon = res.userInfo.avatarUrl;
						// this.userinfo.nickname = res.userInfo.nickName;
						//查詢用戶是否存在
						if(checkUser()){
							//console.log("true>>>>>>>>> ");// this.tohome();
							//console.log(checkUser());
							//console.log(uni.getStorageSync('roles'));
						}else{
							//跳轉註冊
							uni.navigateTo({
								url:'/team/register/selectrole'
							})
						}
						
					},
					fail: (err) => {
						//console.log(err);
					}
				})

			},
			searchLoginRecord() {
				//检查注册流程
				this.$api.post({
					url: '/regedit/status'
				}, {
					unionid: this.unionid
				}).then(res => {
					if (res.regedit == undefined) {
						this.showlogin = true;
					} else if (res.regedit.status == '0') {
						//console.log(res.regedit)
						uni.setStorageSync("regedit", res.regedit);
						uni.setStorageSync("regeditstatus", res.regedit.status);
						uni.navigateTo({
							url: `../../team/register/result`
						})
					} else {
						this.showlogin = true;

					}
				})

				if (this.user != '') {
					// this.tohome(this.roles);
				}
			},
			pwdLogin() {
				this.$api.post({
					url: '/sysuser/login'
				}, this.accont).then(res => {
					if (res.code == "0") {

						//登录成功后，存储账号密码
						// uni.setStorageSync('accont', this.accont)
						//console.log(uni.getStorageSync('accont'));
						switch (res.result) {
							case 'password_error':
								this.$refs.uToast.show({
									title: '密码错误',
									type: 'warning',
								});
								break;
							case 'none':
								this.$refs.uToast.show({
									title: '无此用户，请先注册',
									type: 'warning',
								});
								break;
							case 'overtime':
								this.$refs.uToast.show({
									title: '服务到期，请联系学校管理员',
									type: 'warning',
								});
								break;
							default:
								uni.setStorageSync("user", res.user);
								uni.setStorageSync("roles", res.roles);
								//console.log(res.roles)
								uni.setStorageSync('role', res.roles[0]);
								// //console.log(">>>>>unionid    " + this.unionid)
								// //console.log(res.user)
								if (res.user.unionid == '') {
									this.updateUser(res.user.id, res.roles); //更新用户unionid信息
								} else {
									this.tohome(res.roles);
								}
								break;
						}
					}
				})
			},
			//获取手机号
			getPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					uni.login({
						provider: 'weixin',
						success: (res) => {
							//console.log(">>>>>>>>wxlogin-----");
							//console.log(res);
							let opts = {
								url: '/comm/getPhoneFromApplet',
								method: 'post'
							};
							let param = {
								encryptedData: e.detail.encryptedData,
								iv: e.detail.iv,
								code: res.code
							};
							this.$api.post(opts, param).then(resp => {
								//console.log("resp>>>>>>>>>>>");
								//console.log(resp);
								this.accont = {
									mobile: resp.phoneNumber,
									pwd: '',
								}
								this.codeLogin()
							})
						}
					})
				}

			},
			codeLogin() {
				let params = {
					mobile: this.accont.mobile,
					pwd: ''
				};
				this.$api.post({
					url: '/sysuser/mobilelogin'
				}, params).then(res => {
					if (res.code == "0") {
						//登录成功后，存储账号密码
						uni.setStorageSync('accont', params)
						//console.log(uni.getStorageSync('accont'));
						switch (res.result) {
							case 'password_error':
								this.$refs.uToast.show({
									title: '密码错误',
									type: 'warning',
								});
								break;
							case 'none':
								this.$refs.uToast.show({
									title: '无此用户，请先注册',
									type: 'warning',
									url: '/team/register/selectrole'
								});
								break;
							case 'overtime':
								this.$refs.uToast.show({
									title: '服务到期，请联系学校管理员',
									type: 'warning',
								});
								break;
							default:
								uni.setStorageSync("user", res.user);
								uni.setStorageSync("roles", res.roles);
								//console.log(res.roles)
								uni.setStorageSync('role', res.roles[0]);
								//console.log(">>>>>unionid    " + this.unionid)
								//console.log(res.user)
								if (res.user.unionid == '') {
									this.updateUser(res.user.id, res.roles); //更新用户unionid信息
								} else {
									this.tohome(res.roles);
								}
								break;
						}
					}
				})
			},
			inputauthcode() {
				if (this.form.code.length == 6) {
					if (this.form.code != this.authcode) {
						this.$refs.uToast.show({
							title: '验证码错误',
							type: 'default'
						})
					} else if (this.miao <= 1) {
						this.$refs.uToast.show({
							title: '验证码过期',
							type: 'default'
						})
					}
				}
			},
			//登录
			login() {
				if (this.changeLogin == true) {
					if (this.form.usercode == "") {
						this.$refs.uToast.show({
							title: '请输入账号',
							type: 'warning',
						});
					} else if (this.form.pwd == "") {
						this.$refs.uToast.show({
							title: '请输入密码',
							type: 'warning',
						});
					} else {
						wx.vibrateShort();
						this.$api.post({
							url: '/sysuser/login'
						}, this.form).then(res => {
							if (res.code == "0") {

								//登录成功后，存储账号密码
								uni.setStorageSync('accont', this.form)
								//console.log(uni.getStorageSync('accont'));
								switch (res.result) {
									case 'password_error':
										this.$refs.uToast.show({
											title: '密码错误',
											type: 'warning',
										});
										break;
									case 'none':
										this.$refs.uToast.show({
											title: '无此用户，请先注册',
											type: 'warning',
										});
										break;
									case 'overtime':
										this.$refs.uToast.show({
											title: '服务到期，请联系学校管理员',
											type: 'warning',
										});
										break;
									default:
										uni.setStorageSync("user", res.user);
										uni.setStorageSync("roles", res.roles);
										//console.log(res.roles)
										uni.setStorageSync('role', res.roles[0]);
										//console.log(">>>>>unionid    " + this.unionid)
										//console.log(res.user)
										if (res.user.unionid == '') {
											this.updateUser(res.user.id, res.roles); //更新用户unionid信息
										} else {
											this.tohome(res.roles);
										}
										break;
								}
							}
						})
					}
				} else {
					if (this.form.usercode == "") {
						this.$refs.uToast.show({
							title: '请输入账号',
							type: 'warning',
						});
					} else if (this.form.code.length == 6) {
						//console.log(this.form.code != this.authcode);
						if (this.form.code != this.authcode) {
							this.$refs.uToast.show({
								title: '验证码错误',
								type: 'default'
							})
						} else if (this.miao <= 1) {
							this.$refs.uToast.show({
								title: '验证码过期',
								type: 'default'
							})
						} else {
							let params = {
								mobile: this.form.usercode,
								pwd: ''
							};
							this.$api.post({
								url: '/sysuser/mobilelogin'
							}, params).then(res => {
								if (res.code == "0") {
									//登录成功后，存储账号密码
									uni.setStorageSync('accont', this.form)
									//console.log(uni.getStorageSync('accont'));
									switch (res.result) {
										case 'password_error':
											this.$refs.uToast.show({
												title: '密码错误',
												type: 'warning',
											});
											break;
										case 'none':
											this.$refs.uToast.show({
												title: '无此用户，请先注册',
												type: 'warning',
											});
											break;
										case 'overtime':
											this.$refs.uToast.show({
												title: '服务到期，请联系学校管理员',
												type: 'warning',
											});
											break;
										default:
											uni.setStorageSync("user", res.user);
											uni.setStorageSync("roles", res.roles);
											//console.log(res.roles)
											uni.setStorageSync('role', res.roles[0]);
											//console.log(">>>>>unionid    " + this.unionid)
											//console.log(res.user)
											if (res.user.unionid == '') {
												this.updateUser(res.user.id, res.roles); //更新用户unionid信息
											} else {
												this.tohome(res.roles);
											}
											break;
									}
								}
							})
						}
					} else {
						this.$refs.uToast.show({
							title: '验证码错误',
							type: 'default'
						})
					}
				}

			},
			//自动登录

			//注册
			regist() {
				uni.navigateTo({
					url: `/team/register/selectrole`
				})
			},
			//验证码
			createCode() { //生成6位随机数
				var code = '';
				var codeLength = 6;
				var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
				for (var i = 0; i < codeLength; i++) {
					var index = Math.floor(Math.random() * 9);
					code += random[index];
				}
				return code;
			},
			//发送验证码
			getpostcode() {
				var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
				if (this.form.usercode.length == 0) {
					this.$refs.uToast.show({
						title: '请获取手机号',
						type: 'default',
					})
					return;
				}
				if (!myreg.test(this.form.usercode) || this.form.usercode.length !== 11) {
					this.$refs.uToast.show({
						title: '请输入正确的手机号格式',
						type: 'default'
					})
					return;
				}
				this.authcode = this.createCode()
				// //console.log('验证码' + this.authcode)
				// this.form.code = this.authcode
				// return
				this.$api.post({
					url: '/comm/sendMsg'
				}, {
					mobile: this.form.usercode,
					authCode: this.authcode
				}).then(res => {
					//console.log('><>>' + res)
					if (res == "success") {
						this.$refs.uToast.show({
							title: '已发送成功',
							type: 'default',
						})
						this.getCode()
					} else {
						uni.showToast({
							title: '接口问题',
							icon: 'none'
						})
					}
				})
			},

			//倒计时
			getCode() {
				wx.vibrateShort();
				if (!this.timer) {
					// 通知验证码组件内部开始倒计时
					this.miao = 180;
					this.able = true;
					this.timer = setInterval(() => {
						if (this.miao > 0 && this.miao <= 180) {
							this.miao--;
							if (this.miao == 1) {
								this.authcode = "";
								this.sendcodetext = '发送'
							}
						} else {
							clearInterval(this.timer)
							this.able = false;
							this.timer = null
						}
					}, 1000);
				}
			},
			tohome(roles) {
				if (roles.length == 1) {
					let ur = uni.getStorageSync("user");
					if (roles[0] == 'tr') {
						this.$api.post({
							url: '/yschool/getById'
						}, {
							id: ur.schoolId
						}).then(res => {
							uni.setStorageSync("currSchool", res.school)
							uni.reLaunch({
								url: '/pages/home/home'
							})
						})
					} else if (roles[0] == 'stu') {
						uni.reLaunch({
							url: '/pageHome/stuhome/home'
						})
					} else if (roles[0] == 'team') {
						let _this = this;
						//agree
						wx.requestSubscribeMessage({
							tmplIds: ['D1_iDgju0SYeeckTOOWkgndTWQpr6hLNdHZDZxlPmj4'],
							success(rs) {
								if (JSON.stringify(rs).indexOf('accept') > 0) {
									//console.log("同意");
								} else {
									//console.log("拒绝")
								}
								_this.$api.post({
									url: '/yschool/getById'
								}, {
									id: ur.schoolId
								}).then(res => {
									uni.setStorageSync("userSchool", res.school)
									uni.reLaunch({
										url: '/team/kc/changeSchool'
									})
								})
							},
							fail(rs) {
								//console.log(rs)
							},
						})
					} else if (roles[0] == 'admin') {
						this.$api.post({
							url: '/yschool/getById'
						}, {
							id: ur.schoolId
						}).then(res => {
							uni.setStorageSync("currSchool", res.school)
							uni.reLaunch({
								url: '/team/schoolHome'
							})
						})
					}
				} else if (roles.length > 1) {
					uni.reLaunch({
						url: '/pages/index/selectRole'
					})
				}
			},
			updateUser(userid, roles) {
				this.$api.post({
					url: '/sysuser/modifyUnionid'
				}, {
					id: userid,
					appletsOpenid: this.openid,
					unionId: this.unionid
				}).then(s => {
					// //console.log(">>update user unionid success");
					this.tohome(roles);
				})
			},
			getUnionidOnly() {
				return
				wx.login({
					success: res => {
						var _this = this;
						_this.$api.post({
							url: '/comm/getAppletUnionid'
						}, {
							code: res.code
						}).then(s => {
							//console.log(s)
							_this.openid = s.openid;
							_this.unionid = s.unionid;
							uni.setStorageSync('openid', s.openid);
							uni.setStorageSync('unionid', s.unionid);
							//console.log(">>>>loginPush（）：");
							// _this.loginPush(scene,s.openid)
							_this.socketLogin()

							//console.log(">>>>当前微信unionid绑定的用户为：" + s.user);
							//console.log(s.user)
							if (s.code != '10012') {
								if (uni.getStorageSync('user') == '') {
									uni.setStorageSync('user', s.user);
									uni.setStorageSync('roles', s.roles);
									uni.setStorageSync('role', s.roles[0]);
								}

							}
							// 检查登录信息
							this.searchLoginRecord();
						})
					}
				})
			},
			changeStatus() {
				this.changeLogin = !this.changeLogin
			}
		}
	}
</script>

<style scoped lang="scss">
	.change {
		width: auto;
		color: #fff;
		font-size: 28rpx;
		border-bottom: 1px solid #fff;
	}

	// .register {
	// 	text-align: center;
	// 	width: 560rpx;
	// 	height: 86rpx;
	// 	line-height: 70rpx;
	// 	font-size: 30rpx;
	// 	color: #d9dbef;
	// 	background: #8387ec;
	// 	border: solid .1px #9db2ff;
	// 	border-radius: 40px;
	// }


	.register {
		// position: fixed;
		// bottom: 80rpx;
		margin-top: 30rpx;
		width: 100%;
		text-align: left;
		color: #fff;
		font-size: 24rpx;
	}

	.fixed {
		// position: fixed;
		// bottom: 80rpx;

		margin-top: 50px;
	}

	.mt66 {
		margin-top: 66rpx;
	}

	.mt150 {
		margin-top: 150rpx;
	}

	.main-cont {
		width: 100%;
		height: 100%;
	}

	.content {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: url(https://yh-sys.oss-cn-beijing.aliyuncs.com/6B9AF39796704A5CB130FC9C0CFB7A28icon_bg.png?Expires=4799124463&OSSAccessKeyId=LTAI4GL8SwAiLh3sSPXDS7z9&Signature=3z2ea85buEEsjoSlp5uw2FIOMoo%3D) no-repeat;
		background-size: 100%;
		color: #fff;
		background-color: #888bf3;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		/* color: #8f8f94; */
		color: $u-type-warning;
	}

	.login-tip {
		font-size: 36rpx;
	}

	.name {
		font-size: 42rpx;
		font-weight: 600;
	}

	.login-btn {
		width: 560rpx;
		height: 86rpx;
		line-height: 86rpx;
		background: linear-gradient(0deg, #DFE2F5, #FFFFFF);
		box-shadow: 0px 14rpx 40rpx 0px #626BF1;
		border-radius: 43rpx;
		font-size: 34rpx;
		text-align: center;
		color: #626BF1;
		font-weight: 600;
	}

	.list {
		padding: 0 3rpx 0 34rpx;
		position: relative;
		width: 560rpx;
		height: 78rpx;
		background: #6E75F1;
		border: 2rpx solid #E9EAFF;
		border-radius: 39rpx;

		.items {
			width: 100%;
			height: 100%;
		}

		.tips {
			margin-top: 10rpx;
			width: 100%;
			margin-left: 20rpx;
			font-size: 20rpx;
			color: #D5D9F5;
		}

		.send-code {
			width: 230rpx;
			height: 70rpx;
			line-height: 70rpx;
			background: linear-gradient(0deg, #DFE2F5, #FFFFFF);
			border-radius: 35rpx;
			text-align: center;
			color: #626BF1;
			font-size: 24rpx;
		}

		&:nth-child(4) {
			padding-right: 5rpx;
		}
	}
</style>
